# coding: utf-8

import logging
import datetime
import time
import requests
import json

from sqlalchemy import create_engine
from sqlalchemy.sql import text


# BASE_MISSING_CALL_URL = 'http://127.0.0.1:5000/outbound/sync/guide'

BASE_MISSING_CALL_URL = 'http://opc.wanpinghui.com/outbound/sync/guide'

DB_USER = 'cc'
DB_PWD = 'cc'
DB_HOST = '192.168.1.208:1521'
DB_NAME = 'orcl'
cc_engine = create_engine(
    'oracle+cx_oracle://%s:%s@%s/%s' % (
        DB_USER, DB_PWD, DB_HOST, DB_NAME
    )
)

cc_conn = cc_engine.connect()


sql = text("""
select
    ky.F_LastAgent_OnCall(nxcallid) as cAgentID, corgani
from
    ky.t_imr_calllog
where
    NTYPE=1 and tbegin>:tbegin
    and corgdnis = '4009980215'
    and itenantid=202
""")


while True:
    try:
        now = datetime.datetime.now()
        delta = datetime.timedelta(minutes=30)
        select_result = cc_conn.execute(
            sql,
            tbegin=now.date()
        )
        result_list = list(select_result)
        data = [
            dict(mobile=each[1], agent_id=each[0])
            for each in result_list
        ]
        logging.warning(json.dumps(data))
        r = requests.post(BASE_MISSING_CALL_URL, json={'data_list': data})
        logging.warning(r.text)

    except Exception as e:
        logging.warning(str(e))

    logging.warning("run at: %s" % datetime.datetime.now())
    time.sleep(60*30)
